/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.*;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author facundo
 */
public class BalanceCaja extends JPanel {

    public static JFrame frame;
    String rangoFechas;
    Date fechaComp;
    List<Caja> ingresosList = new ArrayList<Caja>();
    List<Caja> egresosList = new ArrayList<Caja>();

    public JFrame getFrame() {
        return frame;
    }
    private Usuarios usuario;

    public BalanceCaja(Usuarios usuario) {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.usuario = usuario;
        rangoFechas = "D";
        buttonGroup1.add(diaRadioButton);
        buttonGroup1.add(semanaRadioButton);
        buttonGroup1.add(mesRadioButton);
        buttonGroup1.add(anoRadioButton);
        diaRadioButton.setSelected(true);
        calcularBalance(rangoFechas);
        cargarEgresosTable();
        cargarIngresosTable();
    }

    public static String imprimirReferencia(String letra) {
        String retorno = "";
        switch (letra) {
            case "B":
                retorno = "Alquiler";
                break;
            case "C":
                retorno = "Reserva";
                break;
            case "F":
                retorno = "Reserva Firme";
                break;
            case "O":
                retorno = "Alquiler";
                break;
            case "R":
                retorno = "Reserva";
                break;
        }
        return retorno;
    }

    public void cargarEgresosTable() {
        DefaultTableModel temp = (DefaultTableModel) egresosTable.getModel();
        List<Alquileres> referenciaEgresos = new ArrayList<>();
        String referenciaStr = "";
        Integer idAlquiler;

        if (egresosTable.getRowCount() > 0) {
            while (egresosTable.getRowCount() > 0) {
                temp.removeRow(0);
            }
        }

        if (egresosList != null) {
            for (int i = 0; i < egresosList.size(); i++) {
                Query queryUsuario = entityManager.createNamedQuery("Usuarios.findByIdUsuario");
                queryUsuario.setParameter("idUsuario", egresosList.get(i).getResponsable());
                Usuarios usuarioMov = (Usuarios) queryUsuario.getSingleResult();

                Query queryOperacion = entityManager.createNamedQuery("Operaciones.findById");
                queryOperacion.setParameter("id", egresosList.get(i).getOperacion());
                Operaciones operacion = (Operaciones) queryOperacion.getSingleResult();

                Query queryReferencia = entityManager.createNamedQuery("Alquileres.findByIdAlquiler");
                try {
                    idAlquiler = Integer.parseInt(egresosList.get(i).getObservaciones());
                    queryReferencia.setParameter("idAlquiler", idAlquiler);
                    //Si se pudo hacer el parse es xq contiene el id del alquiler
                    referenciaEgresos = queryReferencia.getResultList();
                    //Por lo tanto tengo que procesar la referencia
                    if (!referenciaEgresos.isEmpty()) {
                        referenciaStr = imprimirReferencia(referenciaEgresos.get(0).getTipoAlquiler()) + " ID: " + referenciaEgresos.get(0).getIdAlquiler();
                    } 
                } catch (NumberFormatException nfex) {
                    //Si no se pudo hacer el parse de las observaciones es xq no contenia ID (es decir, era un retiro de efectivo)
                    if (!referenciaEgresos.isEmpty()) {
                        referenciaStr = egresosList.get(i).getObservaciones();
                    }
                }

                Calendar cal = Calendar.getInstance();
                cal.setTime(egresosList.get(i).getFecha());
                String fechaMovimiento = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);

                //Object nuevo[] = {usuarioMov.getNombre(), fechaMovimiento, operacion.getOperacion(), egresosList.get(i).getImporte(), egresosList.get(i).getMoneda(), referenciaStr};
                Object nuevo[] = {usuarioMov.getNombre(), fechaMovimiento, operacion.getOperacion(), egresosList.get(i).getImporte(), egresosList.get(i).getMoneda(), egresosList.get(i).getObservaciones()};
                temp.addRow(nuevo);
            }
        }
    }

    public void cargarIngresosTable() {
        DefaultTableModel temp = (DefaultTableModel) ingresosTable.getModel();
        List<Alquileres> referenciaIngresos = new ArrayList<>();
        String referenciaStr = "";
        Integer idAlquiler;

        if (ingresosTable.getRowCount() > 0) {
            while (ingresosTable.getRowCount() > 0) {
                temp.removeRow(0);
            }
        }

        if (ingresosList != null) {
            for (int i = 0; i < ingresosList.size(); i++) {
                Query queryUsuario = entityManager.createNamedQuery("Usuarios.findByIdUsuario");
                queryUsuario.setParameter("idUsuario", ingresosList.get(i).getResponsable());
                Usuarios usuarioMov = (Usuarios) queryUsuario.getSingleResult();

                Query queryOperacion = entityManager.createNamedQuery("Operaciones.findById");
                queryOperacion.setParameter("id", ingresosList.get(i).getOperacion());
                Operaciones operacion = (Operaciones) queryOperacion.getSingleResult();

                Query queryReferencia = entityManager.createNamedQuery("Alquileres.findByIdAlquiler");
                try {
                    idAlquiler = Integer.parseInt(ingresosList.get(i).getObservaciones());
                    queryReferencia.setParameter("idAlquiler", idAlquiler);
                    //Si se pudo hacer el parse es xq contiene el id del alquiler
                    referenciaIngresos = queryReferencia.getResultList();
                    //Por lo tanto tengo que procesar la referencia
                    if (!referenciaIngresos.isEmpty()) {
                        referenciaStr = imprimirReferencia(referenciaIngresos.get(0).getTipoAlquiler()) + " ID: " + referenciaIngresos.get(0).getIdAlquiler();
                    } 
                } catch (NumberFormatException nfex) {
                    //Si no se pudo hacer el parse de las observaciones es xq no contenia ID (es decir, era un retiro de efectivo)
                    if (!referenciaIngresos.isEmpty()) {
                        referenciaStr = ingresosList.get(i).getObservaciones();
                    }
                }


                //String referenciaStr = ingresosList.get(i).getObservaciones();


                /*
                 * if (!referenciaIngresos.isEmpty()) { referenciaStr =
                 * imprimirReferencia(referenciaIngresos.get(0).getTipoAlquiler())
                 * + " ID: " + referenciaIngresos.get(0).getIdAlquiler(); }
                 */

                Calendar cal = Calendar.getInstance();
                cal.setTime(ingresosList.get(i).getFecha());
                String fechaMovimiento = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);

                //Object nuevo[] = {usuarioMov.getNombre(), fechaMovimiento, operacion.getOperacion(), ingresosList.get(i).getImporte(), ingresosList.get(i).getMoneda(), referenciaStr};
                Object nuevo[] = {usuarioMov.getNombre(), fechaMovimiento, operacion.getOperacion(), ingresosList.get(i).getImporte(), ingresosList.get(i).getMoneda(), ingresosList.get(i).getObservaciones()};
                temp.addRow(nuevo);
            }
        }
    }

    public void calcularBalance(String rango) {
        egresosList.clear();
        ingresosList.clear();
        Double totalPesos = 0.0;
        Double totalDolares = 0.0;
        Double totalIngresos = 0.0;
        Double totalEgresos = 0.0;
        Date fechaComparacion = new Date();
        Calendar fechaActual = Calendar.getInstance();
        int diadelmes = fechaActual.get(Calendar.MONTH) + 1;

        tituloLabel.setText("Balance de caja al dia " + fechaActual.get(Calendar.DATE) + "/" + diadelmes + "/" + fechaActual.get(Calendar.YEAR));

        Calendar fechaRango = Calendar.getInstance();

        switch (rangoFechas) {
            case "D":
                ingresosLabel.setText("Total ingresos del dia");
                egresosLabel.setText("Total egresos del dia");
                fechaRango.add(Calendar.DATE, -1);
                fechaComparacion = fechaRango.getTime();
                break;
            case "S":
                ingresosLabel.setText("Total ingresos de la semana");
                egresosLabel.setText("Total egresos de la semana");
                fechaRango.add(Calendar.DATE, -7);
                fechaComparacion = fechaRango.getTime();
                break;
            case "M":
                ingresosLabel.setText("Total ingresos del mes");
                egresosLabel.setText("Total egresos del mes");
                fechaRango.add(Calendar.MONTH, -1);
                fechaComparacion = fechaRango.getTime();
                break;
            case "A":
                ingresosLabel.setText("Total ingresos del año");
                egresosLabel.setText("Total egresos del año");
                fechaRango.add(Calendar.YEAR, -1);
                fechaComparacion = fechaRango.getTime();
                break;
        }

        fechaComp = fechaComparacion;

        // Buscar movimientos
        Query queryMovimientos = entityManager.createNamedQuery("Caja.findUnderFecha");
        queryMovimientos.setParameter("fecha", fechaComparacion);
        List<Caja> balanceList = queryMovimientos.getResultList();

        for (int i = 0; i < balanceList.size(); i++) {
            Double cambio = getCotizacion(balanceList.get(i).getMoneda());
            // Si la operacion es extraccion de dinero
            if (balanceList.get(i).getOperacion() == 3) {
                totalEgresos = totalEgresos + (balanceList.get(i).getImporte() * cambio);
                egresosList.add(balanceList.get(i));
            } else {
                totalIngresos = totalIngresos + (balanceList.get(i).getImporte() * cambio);
                ingresosList.add(balanceList.get(i));
            }

            // Si el movimiento es en dolares
            if ("USD".equals(balanceList.get(i).getMoneda())) {
                // Si es retiro de efectivo "RESTO"
                if (balanceList.get(i).getOperacion() == 3) {
                    totalDolares = totalDolares -balanceList.get(i).getImporte();
                    // Si es operacion != retiro de efectivo "SUMO"
                } else {
                    totalDolares = totalDolares + balanceList.get(i).getImporte();
                }
                // Si el movimiento es en una moneda diferente a dolares transformo a pesos
            } else {
                // Si es retiro de efectivo "RESTO"
                if (balanceList.get(i).getOperacion() == 3) {
                    totalPesos = totalPesos - (balanceList.get(i).getImporte() * cambio);
                    // Si es operacion != retiro de efectivo "SUMO"
                } else {
                    totalPesos = totalPesos + (balanceList.get(i).getImporte() * cambio);
                }
            }
        }

        ingresosTextField.setText(totalIngresos + " ARS");
        egresosTextField.setText(totalEgresos + " ARS");
        balancePesosTextField.setText(totalPesos + " ARS");
        balanceDolaresTextField.setText(totalDolares + " USD");
    }

    public double getCotizacion(String moneda) {
        Double cambio;
        // Buscar cotizaciones
        Query queryCotizacion = entityManager.createNamedQuery("Moneda.findByClave");
        queryCotizacion.setParameter("clave", moneda);
        List<Moneda> cotizacionesList = queryCotizacion.getResultList();
        cambio = cotizacionesList.get(0).getCambio();
        return cambio;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Caja c WHERE c.operacion != 3");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        buttonGroup1 = new javax.swing.ButtonGroup();
        masterScrollPane = new javax.swing.JScrollPane();
        ingresosTable = new javax.swing.JTable();
        tituloLabel = new javax.swing.JLabel();
        balancePesosTextField = new javax.swing.JTextField();
        balanceDolaresTextField = new javax.swing.JTextField();
        ingresosLabel = new javax.swing.JLabel();
        egresosLabel = new javax.swing.JLabel();
        ingresosTextField = new javax.swing.JTextField();
        egresosTextField = new javax.swing.JTextField();
        diaRadioButton = new javax.swing.JRadioButton();
        semanaRadioButton = new javax.swing.JRadioButton();
        mesRadioButton = new javax.swing.JRadioButton();
        anoRadioButton = new javax.swing.JRadioButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        egresosTable = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();

        FormListener formListener = new FormListener();

        ingresosTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Responsable", "Fecha", "Operacion", "Importe", "Moneda", "Referencia"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        masterScrollPane.setViewportView(ingresosTable);

        tituloLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        tituloLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/balance.png"))); // NOI18N
        tituloLabel.setText("Balance de caja");

        balancePesosTextField.setEditable(false);
        balancePesosTextField.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N

        balanceDolaresTextField.setEditable(false);
        balanceDolaresTextField.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N

        ingresosLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        ingresosLabel.setText("Total ingresos");

        egresosLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        egresosLabel.setText("Total egresos");

        ingresosTextField.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        ingresosTextField.setForeground(new java.awt.Color(0, 51, 255));

        egresosTextField.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        egresosTextField.setForeground(new java.awt.Color(204, 0, 0));

        diaRadioButton.setText("Balance del dia");
        diaRadioButton.addActionListener(formListener);

        semanaRadioButton.setText("Balance semanal");
        semanaRadioButton.addActionListener(formListener);

        mesRadioButton.setText("Balance mensual");
        mesRadioButton.addActionListener(formListener);

        anoRadioButton.setText("Balance anual");
        anoRadioButton.addActionListener(formListener);

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/logoPequeSiaat.png"))); // NOI18N

        jLabel5.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N
        jLabel5.setText("Ingresos de dinero");

        jLabel6.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N
        jLabel6.setText("Egresos de dinero");

        egresosTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Responsable", "Fecha", "Operacion", "Importe", "Moneda", "Referencia"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.Double.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(egresosTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addComponent(jSeparator2)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(egresosLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(egresosTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ingresosLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(ingresosTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(balancePesosTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(balanceDolaresTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(tituloLabel))
                                .addGap(192, 192, 192)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(anoRadioButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(mesRadioButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(semanaRadioButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(diaRadioButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(15, 15, 15)
                        .addComponent(diaRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(semanaRadioButton))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tituloLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(balancePesosTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(balanceDolaresTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mesRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(anoRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ingresosTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ingresosLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(egresosLabel)
                    .addComponent(egresosTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == diaRadioButton) {
                BalanceCaja.this.diaRadioButtonActionPerformed(evt);
            }
            else if (evt.getSource() == semanaRadioButton) {
                BalanceCaja.this.semanaRadioButtonActionPerformed(evt);
            }
            else if (evt.getSource() == mesRadioButton) {
                BalanceCaja.this.mesRadioButtonActionPerformed(evt);
            }
            else if (evt.getSource() == anoRadioButton) {
                BalanceCaja.this.anoRadioButtonActionPerformed(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    private void diaRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_diaRadioButtonActionPerformed
        rangoFechas = "D";
        calcularBalance(rangoFechas);
        cargarEgresosTable();
        cargarIngresosTable();
    }//GEN-LAST:event_diaRadioButtonActionPerformed

    private void semanaRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_semanaRadioButtonActionPerformed
        rangoFechas = "S";
        calcularBalance(rangoFechas);
        cargarEgresosTable();
        cargarIngresosTable();
    }//GEN-LAST:event_semanaRadioButtonActionPerformed

    private void mesRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mesRadioButtonActionPerformed
        rangoFechas = "M";
        calcularBalance(rangoFechas);
        cargarEgresosTable();
        cargarIngresosTable();
    }//GEN-LAST:event_mesRadioButtonActionPerformed

    private void anoRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anoRadioButtonActionPerformed
        rangoFechas = "A";
        calcularBalance(rangoFechas);
        cargarEgresosTable();
        cargarIngresosTable();
    }//GEN-LAST:event_anoRadioButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton anoRadioButton;
    private javax.swing.JTextField balanceDolaresTextField;
    private javax.swing.JTextField balancePesosTextField;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JRadioButton diaRadioButton;
    private javax.swing.JLabel egresosLabel;
    private javax.swing.JTable egresosTable;
    private javax.swing.JTextField egresosTextField;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JLabel ingresosLabel;
    private javax.swing.JTable ingresosTable;
    private javax.swing.JTextField ingresosTextField;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private java.util.List<entities.Caja> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JRadioButton mesRadioButton;
    private javax.persistence.Query query;
    private javax.swing.JRadioButton semanaRadioButton;
    private javax.swing.JLabel tituloLabel;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios usuario) {
        final Usuarios usuarioActual = usuario;
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BalanceCaja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BalanceCaja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BalanceCaja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BalanceCaja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        BalanceCaja.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                frame.setContentPane(new BalanceCaja(usuarioActual));
                //VistaCaja.frame = frame;
                frame.setTitle("Balance de Caja - SIAAT");
                frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        if (frame != null){
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
